package com.itheima.health.controller;

import com.itheima.health.common.MessageConst;
import com.itheima.health.entity.PageResult;
import com.itheima.health.entity.QueryPageBean;
import com.itheima.health.entity.Result;
import com.itheima.health.pojo.Menu;
import com.itheima.health.pojo.Permission;
import com.itheima.health.service.MenuService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

@Slf4j
@RestController
@RequestMapping("menu")
public class MenuController {

    @DubboReference
    private MenuService menuService;

    @PreAuthorize("hasAuthority('MENU_QUERY')")
    @GetMapping("findPage")
    public Result findPage(QueryPageBean queryPageBean){
        PageResult pageResult = menuService.findPage(queryPageBean);
        if (pageResult==null){
            return new Result(false, MessageConst.QUERY_MENU_FAIL);
        }
        return new Result(true,MessageConst.QUERY_MENU_SUCCESS,pageResult);
    }

    @PreAuthorize("hasAuthority(MENU_ADD)")
    @PostMapping("add")
    public Result add(@RequestBody Menu menu){
        boolean flag = menuService.add(menu);
        if (!flag){
            return new Result(false,MessageConst.ADD_MENU_FAIL);
        }
        return new Result(true,MessageConst.ADD_MENU_SUCCESS);
    }

    @PreAuthorize("hasAuthority('MENU_QUERY')")
    @GetMapping("findById")
    public Result findById(Integer id){
        Menu menu = menuService.findById(id);
        if (menu == null){
            return new Result(false,MessageConst.QUERY_MENU_FAIL);
        }
        return new Result(true,MessageConst.QUERY_MENU_SUCCESS,menu);
    }

    @PreAuthorize("hasAuthority('MENU_EDIT')")
    @PostMapping("update")
    public Result update(@RequestBody Menu menu){
        boolean flag = menuService.update(menu);
        if (!flag){
            return new Result(false,MessageConst.EDIT_MENU_FAIL);
        }
        return new Result(true,MessageConst.EDIT_MENU_SUCCESS);
    }

    @PreAuthorize("hasAuthority('MENU_DELETE')")
    @GetMapping("delete")
    public Result delete(Integer id){
        boolean flag = menuService.deleteById(id);
        if (!flag){
            return new Result(false,MessageConst.QUERY_MENU_FAIL);
        }
        return new Result(true,MessageConst.QUERY_MENU_SUCCESS);
    }
}
